package org.example.gui.listener;

import org.example.dao.RecordDAO;
import org.example.entity.Category;
import org.example.gui.panel.HistoryPanel;
import org.example.gui.panel.MainPanel;
import org.example.gui.panel.RecordPanel;
import org.example.gui.panel.SpendPanel;
import org.example.gui.widget.HistoryTablePanel;
import org.example.util.GUIUtil;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

/**
 * RecordPanel 的监听器，按钮后会 增改Record
 * 增改由 RecordPanel.instance.updateId 决定 ，默认为 -1 ，可能被 HistoryListPanel 修改
 */

public class RecordListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        RecordPanel panel = RecordPanel.instance;
        //判断数据
        if (panel.cbModel.categoryList.size() == 0) {
            JOptionPane.showMessageDialog(panel, "请先添加分类");
        }
        String spend = panel.tfSpend.getText();
        if (GUIUtil.isEmpty(panel.tfSpend, "输入的金额")) {
            return;
        }
        if (spend.equals("0")) {
            JOptionPane.showMessageDialog(panel, "输入金额有误");
        }
        Category c = panel.getSelectedCategory();
        String comment = panel.tfComment.getText();
        String location = panel.tfLocation.getText();
        Date d = panel.datePick.getDate();
        //根据 updateId 确定模式
        if (panel.updateId < 0) { //默认的添加模式
            RecordDAO.add(Double.parseDouble(spend), c.getId(), comment, location, d);
            JOptionPane.showMessageDialog(panel, "添加成功");
            MainPanel.instance.workingPanel.show(SpendPanel.instance);
        } else { //修改模式
            RecordDAO.update(panel.updateId, Double.parseDouble(spend), c.getId(), comment, location, d);
            JOptionPane.showMessageDialog(panel, "修改成功");
            MainPanel.instance.workingPanel.show(HistoryPanel.instance);
            //重置p.updateId
            panel.updateId = -1;
            //刷新 HistoryListPanel
            HistoryTablePanel.instance.updateData();
        }
    }
}
